<template>
  <div class="pagebox">
    <div class="topFiltrate bg">
      <!-- <div class="topFiltratetitle">车间看板</div> -->
      <p class="colorin" :class="dateType == 1 ? 'activep' : ''" @click="changedate(1)">七天</p>
      <p class="colorin" :class="dateType == 2 ? 'activep' : ''" @click="changedate(2)">本月</p>
      <p class="colorin" :class="dateType == 3 ? 'activep' : ''" @click="changedate(3)">半年</p>
      <p class="colorin" :class="dateType == 4 ? 'activep' : ''" @click="changedate(4)">今年</p>
      <p class="colorin" :class="dateType == 5 ? 'activep' : ''" @click="changedate(5)">
        自定义
        <a-range-picker v-model="rangeDate" :format="dateFormatList" @change="ondateChange" />
      </p>
    </div>
    <div class="app-container aCnopadding">
      <a-row :gutter="10">
        <a-col :span="7">
          <a-row>
            <!-- 设备数量 -->
            <EquipmentNumber :alarmStatues="alarmStatues" :StateCountData="StateCountData" />
          </a-row>
          <a-row>
            <!-- 状态统计 -->
            <stateStatistics :alarmStatues="alarmStatues" :SumStateTimeList="SumStateTime" />
          </a-row>
        </a-col>
        <!-- 加工信息 -->
        <a-col :span="9">
          <orderTask :AllTaskLSIT="AllTaskLSIT" />
        </a-col>
        <!-- 刀具寿命 -->
        <a-col :span="8">
          <WorkingCalendar
            :ShiftByDayList="ShiftByDayList"
            v-if="haveAllDayList"
            :getAllDayList="getAllDayList"
            v-model="calendar"
          />
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <!-- 效率分析 -->
        <a-col :span="7">
          <efficiencyAnalysis :chartData="chartData" @onTabChange="efficiencyonTabChange" />
        </a-col>
        <!-- 生产统计 -->
        <a-col :span="6">
          <productionFigures :productrank="productrank" :timerank="timerank" />
        </a-col>
        <!-- 产量统计 -->
        <a-col :span="7">
          <ProducStatistics :chartDatalineobj="chartDataline" />
        </a-col>
        <!-- 报警分析 -->
        <a-col :span="4">
          <AlarmAnalysis :AlarmList="AlarmList" />
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import '@/unit/rem';
import { initUserInfo, timeCalculation, formatCurrentMonth, getDayAll, getYearAndMonth } from '@/unit/tool';

import stateStatistics from './component/stateStatistics';
import efficiencyAnalysis from './component/efficiencyAnalysis';
import orderTask from './component/orderTask';
import productionFigures from './component/productionFigures';
import WorkingCalendar from './component/WorkingCalendar';
import AlarmAnalysis from './component/AlarmAnalysis';
import ProducStatistics from './component/ProducStatistics';

import api from '@/api/workshop';
import eapi from '@/api/equipment';
import EquipmentNumber from './component/equipmentNumber/index.vue';

const alarmStatues = ['#3FC529', '#FBC225', '#E74629', '#E2E7EE'];

export default {
  name: 'board',
  components: {
    stateStatistics,
    efficiencyAnalysis,
    orderTask,
    productionFigures,
    WorkingCalendar,
    AlarmAnalysis,
    ProducStatistics,
    EquipmentNumber,
  },
  data() {
    let moment = this.$Moment;
    return {
      userName: '',
      name: '',
      role: '',
      compId: '',
      dateType: 1,
      alarmStatues: alarmStatues,
      pieData: [
        { value: '2', name: '运行' },
        { value: '23', name: '待机' },
        { value: '2', name: '报警' },
        {
          value: '2',
          name: '离线',
        },
      ],
      params: {
        pageSize: 3,
        pageNum: 1,
        countSort: 'desc',
        startTime: '2021-05-25 00:00:00',
        endTime: '2021-05-25 23:59:59',
        companyId: '3',
      },
      timeParames: {
        startTime: null,
        endTime: null,
        UserName: null,
        compid: null,
      },
      productrank: [],
      timerank: [],
      AllTaskLSIT: null,
      SumStateTime: null,
      chartDataline: {
        expectedData: null,
        date: null,
      },
      AlarmList: null,
      noTitleKey: 1,
      chartData: {
        expectedData: null,
        date: null,
      },
      rangeDate: null,
      dateFormatList: ['YYYY-MM-DD', 'YYYY-MM-DD'],
      ShiftByDayList: [],
      getAllDayList: [],
      haveAllDayList: false,
      calendar: {},
      StateCountData: {},
    };
  },
  watch: {
    calendar(val) {
      this.calendarChange(val);
    },
  },
  methods: {
    gotoThat() {
      this.$store.commit('board/HeadNavType', 2);
      localStorage.setItem('navType', 2);
      this.$router.push('/equipmentList');
    },
    ondateChange(dates, datestring) {
      this.timeParames.startTime = datestring[0];
      this.timeParames.endTime = datestring[1];
      this.params.startTime = datestring[0] + ' 00:00:00';
      this.params.endTime = datestring[1] + ' 23:59:59';
      this.initData();
    },
    calendarChange(params) {
      this.calendar.startTime = params.startTime;
      this.calendar.endTime = params.endTime;
      // this.getAllDay()
    },
    initData() {
      this.getProduceRank(); //产量排名
      this.gettimeRank();
      this.getAllTask(); //任务列表
      this.getSumStateTime(); //某段时间内各个状态的时间统计
      if (this.dateType == 3 || this.dateType == 4) {
        this.HalfYearProduceSum();
        this.initlineyear();
      } else {
        this.initline();
        this.DayProduceSum();
      }
      this.MacAlarmStatisticByCompId();
    },
    //班次日历
    getAllDay() {
      let params = {
        companyId: this.params.companyId,
        startTime: this.calendar.startTime,
        endTime: this.calendar.endTime,
      };
      this.haveAllDayList = false;
      api.getAllDay(params).then((res) => {
        this.haveAllDayList = true;
        this.getAllDayList = res.data;
      });
    },
    //班次列表
    getShiftByDay() {
      let params = {
        companyId: this.params.companyId,
        day: timeCalculation(new Date(), 'subtract', 0),
        username: this.timeParames.UserName,
      };
      api.getShiftByDay(params).then((res) => {
        this.ShiftByDayList = res.data;
      });
    },
    //时间
    getSumStateTime() {
      let params = {
        companyId: this.params.companyId,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.getSumStateTime(params).then((res) => {
        this.SumStateTime = res.data;
      });
    },
    //任务列表
    getAllTask() {
      let params = {
        companyId: this.params.companyId,
        status: -1,
      };
      api.getAllTask(params).then((res) => {
        this.AllTaskLSIT = res.data.rows;
      });
    },
    //生产统计
    // 获取机床产量排名
    getProduceRank() {
      delete this.params.timeSort;

      let params = {
        pageSize: 3,
        pageNum: 1,
        countSort: 'desc',
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        companyId: this.params.companyId,
      };
      api.getProduceRank(params).then((res) => {
        this.productrank = res.data.rows;
        // console.log(  this.productrank);
      });
    },
    // 获取机床时间排名
    gettimeRank() {
      delete this.params.countSort;
      this.params.timeSort = 'desc';
      console.log(this.params);
      api.getProduceRank(this.params).then((res) => {
        this.timerank = res.data.rows;
        // console.log(this.timerank);
        // console.log(  this.productrank);
      });
    },
    //七天和本月的产量统计
    //时间段内某天的产量
    DayProduceSum() {
      eapi.DayProduceSum(this.timeParames).then((res) => {
        let list = res.Data;
        this.ProduceSum(list);
        // let expectedData = [];
        // let dates = [];
        // list.forEach((item) => {
        //   expectedData.push(item.num);
        //   dates.push(item.day);
        // });
        // this.chartDataline.expectedData = expectedData;
        // this.chartDataline.date = dates;
      });
    },
    //半年内每月产量
    HalfYearProduceSum() {
      eapi.HalfYearProduceSum(this.timeParames).then((res) => {
        let list = res.Data;
        this.ProduceSum(list, 'month');
        // let expectedData = [];
        // let dates = [];
        // list.forEach((item) => {
        //   expectedData.push(item.num);
        //   dates.push(item.day);
        // });
        // this.chartDataline.expectedData = expectedData;
        // this.chartDataline.date = dates;
      });
    },
    //折线图数据转换
    ProduceSum(list, time) {
      let expectedData = [];
      let dates = null;

      if (time == 'month') {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }
      let data = [];
      dates.forEach((items) => {
        let opt = null;
        if (time == 'month') {
          opt = list.find((day) => day.day == items); //每月
        } else {
          opt = list.find((day) => day.day == items); //每天
        }
        console.log(this.chartDataline);
        if (opt) {
          data.push(opt.num);
        } else {
          data.push(0);
        }
      });
      expectedData.push(data);

      this.chartDataline.expectedData = expectedData;
      this.chartDataline.date = dates;
      this.chartDataline.name = ['产量'];
      console.log(this.chartDataline);
    },
    //报警分析
    MacAlarmStatisticByCompId() {
      let params = {
        compId: this.params.companyId,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
      };
      api.MacAlarmStatisticByCompId(params).then((res) => {
        this.AlarmList = res.Data;
      });
    },
    //某时间段开机率
    GroupOnlineRate() {
      eapi.GroupOnlineRate(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, 1, 1);
      });
    },
    //查询时间段内各产线的运行时间（分钟）
    GroupRunTime() {
      eapi.GroupRunTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list);
      });
    },
    //查询时间段内各产线的故障时间（分钟）
    GroupAlarmTime() {
      eapi.GroupAlarmTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list);
      });
    },
    //查询半年内各产线每月的开机率
    HalfYearGroupOnlineRate() {
      eapi.HalfYearGroupOnlineRate(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, 'month', 1);
      });
    },
    //查询厂半年内各产线的运行时间（分钟)
    HalfYearGroupRunTime() {
      eapi.HalfYearGroupRunTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list, 'month');
      });
    },
    //查询厂半年内各产线的故障时间（分钟）
    HalfYearGroupAlarmTime() {
      eapi.HalfYearGroupAlarmTime(this.timeParames).then((res) => {
        let list = res.Data;
        this.havelinedata(list);
      });
    },
    // /格式化年月不带0的
    monthcomplement(val) {
      let month = val.split('-');
      let monthnum = month[1] <= 9 ? '0' + month[1] : month[1];
      let num = month[0] + '-' + monthnum;
      return num;
    },

    //折线图数据转换
    havelinedata(list, time, type) {
      let expectedData = [];
      let name = [];
      let dates = null;

      if (time == 'month') {
        //每月
        let startTime = this.timeParames.startTime.substring(0, 7);
        let endTime = this.timeParames.endTime.substring(0, 7);
        dates = getYearAndMonth(startTime, endTime);
      } else {
        //每天
        dates = getDayAll(this.timeParames.startTime, this.timeParames.endTime);
      }

      list.forEach((item) => {
        let data = [];
        dates.forEach((items) => {
          let opt = null;
          if (time == 'month') {
            opt = item.arrayData.find((day) => this.monthcomplement(day.day) == items); //每月
          } else {
            opt = item.arrayData.find((day) => day.day == items); //每天
          }

          if (opt) {
            if (type == 1) {
              data.push((opt.yData * 100).toFixed(2));
            } else {
              data.push((opt.yData / 60).toFixed(2));
            }
          } else {
            data.push(0);
          }
        });
        expectedData.push(data);
        name.push(item.macsn);
      });
      this.chartData.expectedData = expectedData;
      this.chartData.date = dates;
      this.chartData.name = name;
    },
    //设备数量
    getStateCount() {
      api.getStateCount({ companyId: this.timeParames.compid }).then((res) => {
        this.StateCountData = res.data;
      });
    },
    efficiencyonTabChange(key) {
      this.noTitleKey = key;
      if (this.dateType == 3 || this.dateType == 4) {
        this.initlineyear();
      } else {
        this.initline();
      }
    },
    //折线图
    initline() {
      if (this.noTitleKey == 1) {
        this.GroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.GroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.GroupAlarmTime();
      }
    },
    //半年折线图
    initlineyear() {
      if (this.noTitleKey == 1) {
        this.HalfYearGroupOnlineRate(); //开机率
      } else if (this.noTitleKey == 2) {
        this.HalfYearGroupRunTime(); //运行时间
      } else if (this.noTitleKey == 3) {
        this.HalfYearGroupAlarmTime(); //故障时间
      }
    },
    changedate(i) {
      this.dateType = i;
      switch (i) {
        case 1:
          // 最近7天
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.timeParames.startTime = timeCalculation(new Date(), 'subtract', 6);
          this.params.endTime = timeCalculation(new Date(), 'subtract', 1) + ' 00:00:00';
          this.params.startTime = timeCalculation(new Date(), 'subtract', 7) + ' 23:59:59';

          this.initData();
          break;
        case 2:
          // 本月
          this.timeParames.startTime = formatCurrentMonth('start', 0);
          this.timeParames.endTime = formatCurrentMonth('end', 0);
          this.params.startTime = formatCurrentMonth('start', 0) + ' 00:00:00';
          this.params.endTime = formatCurrentMonth('end', 0) + ' 23:59:59';
          this.initData();
          break;
        case 3:
          // 最近半年
          this.timeParames.startTime = formatCurrentMonth('start', -5);
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.params.startTime = formatCurrentMonth('start', -5) + ' 00:00:00';
          this.params.endTime = timeCalculation(new Date(), 'subtract', 0) + ' 23:59:59';
          // this.HalfYearProduceSum()
          this.initData();
          break;
        case 4:
          // 一年
          let time = formatCurrentMonth('end', 0);
          this.timeParames.startTime = time.substring(0, 4) + '-01-01';
          this.timeParames.endTime = timeCalculation(new Date(), 'subtract', 0);
          this.params.startTime = time.substring(0, 4) + '-01-01' + ' 00:00:00';
          this.params.endTime = timeCalculation(new Date(), 'subtract', 0) + ' 23:59:59';
          // this.HalfYearProduceSum()
          this.initData();
          // break;
          return;
      }
      // this.getChartData()
    },
  },

  mounted() {},
  created() {
    // let roleId = localStorage.getItem('roleId');
    // if (roleId == 1) {
    //   localStorage.setItem('navType', 1);
    //   this.$router.push('/');
    // } else {
    //   localStorage.setItem('navType', 3);
    //   this.$router.push('/distributionMap');
    // }

    // this.$store.commit('board/HeadNavType', 1);
    // localStorage.setItem('navType', 1);

    this.timeParames.UserName = localStorage.getItem('userName');
    this.timeParames.compid = this.params.companyId = localStorage.getItem('compid');
    this.timeParames.startTime = this.params.startTime = timeCalculation(new Date(), 'subtract', 7) + ' 00:00:00';
    this.timeParames.endTime = this.params.endTime = timeCalculation(new Date(), 'subtract', 1) + ' 23:59:59';
    this.calendar.startTime = formatCurrentMonth('start', 0);
    this.calendar.endTime = formatCurrentMonth('end', 0);
    initUserInfo(this);
    this.initData();
    // this.getShiftByDay();
    this.getAllDay();
    this.getStateCount();
  },
};
</script>

<style lang="less" scoped>
@import './light.less';
@import './style';
</style>
